import java.util.concurrent.*;

public class ThreadPoolExample {

    public static void main(String[] args) {
        int corePoolSize = 16;
        int maximumPoolSize = 64;
        long keepAliveTime = 60; // 线程空闲后的存活时间
        TimeUnit unit = TimeUnit.SECONDS;
        // 和使用队列有关，当核心线程都在处理任务的时候，会优先把任务放在workQueue中，而不是立即开辟非核心线程由非核心线程去处理任务
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 使用有界队列

        RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); // 可选：自定义拒绝策略

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                handler);

        // 提交200个任务
        for (int i = 0; i < 200; i++) {
            executor.submit(new Task());
        }

        // 关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成
            if (!executor.awaitTermination(600, TimeUnit.SECONDS)) { // 增加超时时间以确保所有任务完成
                executor.shutdownNow();
            }
        } catch (InterruptedException ex) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    // 定义任务
    static class Task implements Runnable {
        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            System.out.println("Task executed by " + threadName);
            try {
                // 模拟任务执行耗时
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}